package com.hbsc.service;

import com.hbsc.mapper.YqtestDemoMapper;
import com.hbsc.utils.ImageUtil;
import org.apache.jasper.tagplugins.jstl.core.ForEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by 范柳 on 2018/1/2.
 */
@Component
@Transactional
public class ImageService {
    @Autowired
    private YqtestDemoMapper mapper;
    //验证码集合
    private Set<String> setList = new HashSet<>();
    // 验证码字符集
    private static final char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    // 字符数量
    private static final int SIZE = 4;


    public Object[] createImage(){
        List queryCheckCodes = mapper.queryCheckCodeList();
        for(int q=0 ; q<queryCheckCodes.size(); q++){
            Map<String,Object> map = (Map) queryCheckCodes.get(q);
            String checkCode = (String) map.get("payRandomNum");
            setList.add(checkCode);
        }
         StringBuffer sb = new StringBuffer();

         Object[] objects = ImageUtil.createImage();
         String rowCheckCode = (String) objects[0];
         //判定生成验证码是否存在
        while(setList.contains(rowCheckCode)){
            //随机字符
            Random ran = new Random();
            //重新生成随机数
            for (int i = 0; i <SIZE; i++) {
                // 取随机字符索引
                int n = ran.nextInt(chars.length);
                sb.append(chars[n]);
            }
            rowCheckCode = sb.toString();
        }
        //将生成验证码放入集合
        setList.add(rowCheckCode);
        //重新生成验证码图片
        return new Object[]{rowCheckCode, objects[1]};
    }
}
